{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "nbsphinx": "hidden"
   },
   "source": [
    "[Index](Index.ipynb) - [Back](Widget Custom.ipynb)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Asynchronous Widgets\n",
    "\n",
    "This notebook covers two scenarios where we'd like widget-related code to run without blocking the kernel from acting on other execution requests:\n",
    "\n",
    "1. Pausing code to wait for user interaction with a widget in the frontend\n",
    "2. Updating a widget in the background"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Waiting for user interaction"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You may want to pause your Python code to wait for some user interaction with a widget from the frontend. Typically this would be hard to do since running Python code blocks any widget messages from the frontend until the Python code is done.\n",
    "\n",
    "We'll do this in two approaches: using the event loop integration, and using plain generator functions."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Event loop integration\n",
    "\n",
    "If we take advantage of the event loop integration IPython offers, we can have a nice solution using the async/await syntax in Python 3.\n",
    "\n",
    "First we invoke our asyncio event loop. This requires ipykernel 4.7 or later."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%gui asyncio"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We define a new function that returns a future for when a widget attribute changes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import asyncio\n",
    "def wait_for_change(widget, value):\n",
    "    future = asyncio.Future()\n",
    "    def getvalue(change):\n",
    "        # make the new value available\n",
    "        future.set_result(change.new)\n",
    "        widget.unobserve(getvalue, value)\n",
    "    widget.observe(getvalue, value)\n",
    "    return future"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And we finally get to our function where we will wait for widget changes. We'll do 10 units of work, and pause after each one until we observe a change in the widget. Notice that the widget's value is available to us, since it is what the `wait_for_change` future has as a result.\n",
    "\n",
    "Run this function, and change the slider 10 times."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from ipywidgets import IntSlider, Output\n",
    "slider = IntSlider()\n",
    "out = Output()\n",
    "\n",
    "async def f():\n",
    "    for i in range(10):\n",
    "        out.append_stdout('did work ' + str(i) + '\\n')\n",
    "        x = await wait_for_change(slider, 'value')\n",
    "        out.append_stdout('async function continued with value ' + str(x) + '\\n')\n",
    "asyncio.ensure_future(f())\n",
    "\n",
    "slider"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "out"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Generator approach\n",
    "\n",
    "If you can't take advantage of the async/await syntax, or you don't want to modify the event loop, you can also do this with generator functions."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First, we define a decorator which hooks a generator function up to widget change events."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from functools import wraps\n",
    "def yield_for_change(widget, attribute):\n",
    "    \"\"\"Pause a generator to wait for a widget change event.\n",
    "        \n",
    "    This is a decorator for a generator function which pauses the generator on yield\n",
    "    until the given widget attribute changes. The new value of the attribute is\n",
    "    sent to the generator and is the value of the yield.\n",
    "    \"\"\"\n",
    "    def f(iterator):\n",
    "        @wraps(iterator)\n",
    "        def inner():\n",
    "            i = iterator()\n",
    "            def next_i(change):\n",
    "                try:\n",
    "                    i.send(change.new)\n",
    "                except StopIteration as e:\n",
    "                    widget.unobserve(next_i, attribute)\n",
    "            widget.observe(next_i, attribute)\n",
    "            # start the generator\n",
    "            next(i)\n",
    "        return inner\n",
    "    return f"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then we set up our generator."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from ipywidgets import IntSlider, VBox, HTML\n",
    "slider2=IntSlider()\n",
    "\n",
    "@yield_for_change(slider2, 'value')\n",
    "def f():\n",
    "    for i in range(10):\n",
    "        print('did work %s'%i)\n",
    "        x = yield\n",
    "        print('generator function continued with value %s'%x)\n",
    "f()\n",
    "\n",
    "slider2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Modifications\n",
    "\n",
    "The above two approaches both waited on widget change events, but can be modified to wait for other things, such as button event messages (as in a \"Continue\" button), etc."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Updating a widget in the background\n",
    "\n",
    "Sometimes you'd like to update a widget in the background, allowing the kernel to also process other execute requests. We can do this with threads. In the example below, the progress bar will update in the background and will allow the main kernel to do other computations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import threading\n",
    "from IPython.display import display\n",
    "import ipywidgets as widgets\n",
    "import time\n",
    "progress = widgets.FloatProgress(value=0.0, min=0.0, max=1.0)\n",
    "\n",
    "def work(progress):\n",
    "    total = 100\n",
    "    for i in range(total):\n",
    "        time.sleep(0.2)\n",
    "        progress.value = float(i+1)/total\n",
    "\n",
    "thread = threading.Thread(target=work, args=(progress,))\n",
    "display(progress)\n",
    "thread.start()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "nbsphinx": "hidden"
   },
   "source": [
    "[Index](Index.ipynb) - [Back](Widget Custom.ipynb)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
